Ch2 Data Structures

In this part you will learn how to define data structure more than integer, tuples and boolean.

Tuple

Tuple in python is an 1D array that cannot change its content after declariation. The tuple can store differently type of elements. It is defined with parentheses.


In [27]:
(1, 'HKU', 3.0)


Out[27]:
(1, 'HKU', 3.0)

The elements are called using a square bracket with an index starting from zero.


In [54]:
x = (1, 'HKU', 3.0)
print x[0],x[1],x[2]


1 HKU 3.0

You can slice the array using colon, in this case a[start:end] means items start up to end-1


In [29]:
print x[1:2]


('HKU',)

A single colon a[:] means a copy of the whole array.


In [30]:
print x[:]


(1, 'HKU', 3.0)

a[start:] return tuple of items start through the rest of the array.

a[:end] return tuple of items from the beginning through end-1.


In [31]:
print x[:2], x[1:]


(1, 'HKU') ('HKU', 3.0)

more interestingly, they have negative index

a[-1] means last item in the array

a[-2:] means last two items in the array

a[:-2] means everything except the last two items


In [32]:
print x[-1], x[-2], x[-2:] , x[:-2]


3.0 HKU ('HKU', 3.0) (1,)

You may add up the tuple to concatenate


In [33]:
print x + ('Hi', 'HKU', 1e-8)


(1, 'HKU', 3.0, 'Hi', 'HKU', 1e-08)

You may duplicate the items with multiply


In [34]:
print x*2;


(1, 'HKU', 3.0, 1, 'HKU', 3.0)

List

List is very similar to tuple, but list can add or assign items. List is defined by square bracket while tuple is defined by normal bracket. Lets see an example:

This is a tuple with two elements, each element is a list


In [35]:
t = ([1, 2], [3, 4])
print t


([1, 2], [3, 4])

If we change an item directly in the tuple:


In [37]:
t[0] = [10, 20]


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-37-c53a5d7335d3> in <module>()
----> 1 t[0] = [10, 20]

TypeError: 'tuple' object does not support item assignment

If we change to the list element inside the tuple:


In [38]:
t[0][0] = 10; t[0][1] = 20; print t


([10, 20], [3, 4])

We use square bracket to define a list and each element is separated by comma like a tuple


In [39]:
l = [1,2,3,4,5,6,7,8]
print l


[1, 2, 3, 4, 5, 6, 7, 8]

list can add element to it:


In [40]:
l.append(9); print l


[1, 2, 3, 4, 5, 6, 7, 8, 9]

Of course, slicing also works here


In [41]:
start=2
end=5
step=2

print l[start:end] # items start through end-1
print l[start:]    # items start through the rest of the array
print l[:end]      # items from the beginning through end-1
print l[:]         # a copy of the whole array
print l[-1]    # last item in the array
print l[-2:]   # last two items in the array
print l[:-2]   # everything except the last two items

print l[start:end:step] # start through not past end, by step


[3, 4, 5]
[3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
9
[8, 9]
[1, 2, 3, 4, 5, 6, 7]
[3, 5]

Dictionary

Dictionary is more flexible than list and its index is a string, it is defined with curly bracket


In [42]:
passwords = {'Einstein' : 18790314, 'Newton' : 16421225}

Call the item with its index string


In [43]:
print passwords['Einstein'], passwords['Newton']


18790314 16421225

Update an item to dictionary:


In [44]:
passwords.update({'Planck' : 18580423}); print passwords


{'Newton': 16421225, 'Planck': 18580423, 'Einstein': 18790314}

Delete an item from dictionary:


In [45]:
passwords.pop('Einstein'); print passwords


{'Newton': 16421225, 'Planck': 18580423}

Loops

For Loops

for loop is for xxx in yyyy with a colon. Indentate after this line. yyyy shall be an iteratable, i.e. tuple or list or sth that can be iterate.


In [46]:
x = [1,2,3,4,5,6,7,8]
for item in x:
    print item


1
2
3
4
5
6
7
8

In [47]:
s = ['a','c','b','d','e','g','h',8]
for item in s:
    print item


a
c
b
d
e
g
h
8

Range function in python is good in for loop:


In [48]:
for item in range(1,20):
    print item


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

If three input is provided, the last input is the increment:


In [49]:
for item in range(1,20,2):
    print item


1
3
5
7
9
11
13
15
17
19

This is a simple for loop that sum up all squared integer from 1 to 100


In [50]:
s=0
for i in range(1,100):
    s+=i*i
print s


328350

While Loops

While loop read a true/false statement and carry out if the criteria not met.


In [51]:
s=0; i=1
while i<100:
    s+=i*i
    i+=1
print s


328350

Do you know what is calculating in the following script?


In [1]:
m = 20
n = 79
while n != 0:
   r = m % n
   m = n
   n = r
print m


1

In [ ]: